'use strict';

const Service = require('egg').Service;

class FileService extends Service {
  async addFile() {
    const {
      ctx,
      app
    } = this;
    const {
      url,
      name,
      type,
      size,
    } = ctx.request.body;
    const res = await app.mysql.insert('file', {
      url,
      name,
      type,
      size,
      create_time:Date.now()
    });
    return res
  }
  async getList() {
    const {ctx,app} = this;
    const {
      name,
      type,
      pageSize,
      pageIndex
    } = ctx.query;
    let sql = `select * from file where 1=1 `;
    let countSql = `select count(id) as total from file where 1=1 `
    if (name) {
      sql += `and name="${name}" `
      countSql += `and name="${name}" `
    }
    if (type) {
      sql += `and type="${type}" `
      countSql += `and type="${type}" `
    }
    if (pageSize && pageIndex) {
      sql += `limit ${(pageIndex-1)*pageSize},${pageSize} `
    }
    const res = await app.mysql.query(sql);
    const [{
      total
    }] = await app.mysql.query(countSql);
    return {
      data: res,
      total,
    }
  }
  async delFile(){
    const {ctx,app} = this;
    const {id} = ctx.request.body;
    const res = await app.mysql.delete('file',{
      id
    });
    return res
  }
}

module.exports = FileService;